import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '../store/authStore';
import { Toast } from 'antd-mobile';
import WeatherForecast from '../components/WeatherForecast.jsx';
import { getIsLock, getVipExpired, getIsPerpetualVip } from '../utils/storage';

const UserInfo = () => {
  const navigate = useNavigate();
  const { getUserInfo } = useAuthStore();
  const [userInfo, setUserInfo] = useState(null);
  const [weather, setWeather] = useState(null);
  const [isLocked, setIsLocked] = useState(false);
  const [vipRemaining, setVipRemaining] = useState(null);
  const [isPerpetualVip, setIsPerpetualVip] = useState(false);
  const [showWeather, setShowWeather] = useState(false);

  const zodiacSigns = {
    aries: '白羊座',
    taurus: '金牛座',
    gemini: '双子座',
    cancer: '巨蟹座',
    leo: '狮子座',
    virgo: '处女座',
    libra: '天秤座',
    scorpio: '天蝎座',
    sagittarius: '射手座',
    capricorn: '摩羯座',
    aquarius: '水瓶座',
    pisces: '双鱼座',
  };

  useEffect(() => {
    const fetchUserInfo = async () => {
      try {
        const data = await getUserInfo();
        setUserInfo(data);
        setIsLocked(getIsLock());
        setIsPerpetualVip(getIsPerpetualVip());
        if (data.city) {
          const weatherResponse = await fetch(`https://v2.xxapi.cn/api/weather?city=${data.city}`);
          const weatherData = await weatherResponse.json();
          setWeather(weatherData.data);
        }
        const vipExpired = getVipExpired();
        if (vipExpired) {
          const remainingTime = new Date(vipExpired) - new Date();
          setVipRemaining(remainingTime > 0 ? Math.ceil(remainingTime / (1000 * 60 * 60 * 24)) : 0);
        }
      } catch (error) {
        Toast.show({ content: '获取用户信息失败', position: 'center' });
      }
    };

    fetchUserInfo();
  }, [getUserInfo]);

  if (!userInfo) return null;

  return (
    <div style={{ 
        padding: '0.08rem', 
        background: '#f9f9f9', 
        borderRadius: '0.06rem', 
        boxShadow: '0 0.01rem 0.04rem rgba(0,0,0,0.1)', 
        maxWidth: '2.8rem', 
        margin: '0.1rem auto', 
        textAlign: 'center' 
    }}>
        <img 
            src={`${import.meta.env.VITE_API_URL}/api/files/${userInfo.collectionId}/${userInfo.id}/${userInfo.avatar}`} 
            alt={userInfo.username}  
            style={{ 
                width: '0.3rem', 
                height: '0.3rem', 
                borderRadius: '50%', 
                objectFit: 'cover', 
                marginBottom: '0.08rem', 
                transition: 'transform 0.3s', 
                cursor: 'pointer',
            }} 
            onClick={() => navigate('/edit-profile')}
            onMouseEnter={(e) => e.currentTarget.style.transform = 'scale(1.1)'}
            onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}
        />
        <h2 style={{ fontSize: '0.22rem', margin: '0.08rem 0', color: '#333' }}>{userInfo.username}</h2>
        <div style={{ borderTop: '1px solid #eaeaea', padding: '0.08rem 0' }}>
            <p style={{ margin: '0.03rem 0', color: '#555', fontSize: '0.18rem' }}>邮箱: {userInfo.email}</p>
            <p style={{ margin: '0.03rem 0', color: '#555', fontSize: '0.18rem' }}>城市: {userInfo.city}</p>
            <p style={{ margin: '0.03rem 0', color: '#555', fontSize: '0.18rem' }}>出生日期: {userInfo.birth}</p>
            <p style={{ margin: '0.03rem 0', color: '#555', fontSize: '0.18rem' }}>星座: {zodiacSigns[userInfo.constellation.toLowerCase()] || '未知'}</p>
            <p style={{ margin: '0.03rem 0', color: '#555', fontSize: '0.18rem' }}>注册时间: {new Date(userInfo.created).toLocaleDateString()}</p>
        </div>
        {!isLocked ? (
          <div style={{ color: 'red', fontWeight: 'bold', margin: '0.08rem 0', fontSize: '0.18rem' }}>
            该账号已被锁定，请联系管理员解锁。
          </div>
        ) : isPerpetualVip ? (
          <div style={{ color: 'green', fontWeight: 'bold', margin: '0.08rem 0', fontSize: '0.18rem' }}>
            会员状态: 终身会员
          </div>
        ) : (
          <div style={{ color: 'green', fontWeight: 'bold', margin: '0.08rem 0', fontSize: '0.18rem' }}>
            会员剩余时间: {vipRemaining} 天
          </div>
        )}
        {weather && (
          <div>
            <div 
              style={{
                padding: '0.06rem 0.12rem',
                background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                color: 'white',
                borderRadius: '0.04rem',
                cursor: 'pointer',
                fontSize: '0.16rem',
                fontWeight: 'bold',
                textAlign: 'center',
                margin: '0.08rem 0',
                transition: 'all 0.3s ease',
                boxShadow: '0 0.02rem 0.08rem rgba(0,0,0,0.2)'
              }}
              onClick={() => setShowWeather(!showWeather)}
              onMouseEnter={(e) => e.currentTarget.style.transform = 'scale(1.02)'}
              onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}
            >
              {showWeather ? '隐藏天气信息' : '查看天气信息'}
            </div>
            {showWeather && (
              <div className="slide-down-animation">
                <WeatherForecast weatherData={weather} />
              </div>
            )}
          </div>
        )}
        <div 
          style={{
            padding: '0.06rem 0.12rem',
            background: 'linear-gradient(135deg, #eaa666ff 0%, #764ba2 100%)',
            color: '#333',
            border: '1px solid #eaeaea',
            borderRadius: '0.04rem',
            cursor: 'pointer',
            fontSize: '0.16rem',
            fontWeight: 'bold',
            textAlign: 'center',
            margin: '0.08rem 0',
            transition: 'all 0.3s ease',
            boxShadow: '0 0.01rem 0.03rem rgba(0,0,0,0.1)'
          }}
          onClick={() => navigate('/fen')}
          onMouseEnter={(e) => {
            e.currentTarget.style.transform = 'scale(1.02)';
            e.currentTarget.style.background = '#f5f5f5';
            e.currentTarget.style.boxShadow = '0 0.02rem 0.06rem rgba(0,0,0,0.15)';
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.transform = 'scale(1)';
            e.currentTarget.style.background = '#ffffff';
            e.currentTarget.style.boxShadow = '0 0.01rem 0.03rem rgba(0,0,0,0.1)';
          }}
        >
          查看今日运势
        </div>
    </div>
  );
};

export default UserInfo;
